package cn.xwt.weidisk.controller;

import cn.xwt.weidisk.constant.ErrorCode;
import cn.xwt.weidisk.constant.ServiceError;
import cn.xwt.weidisk.pojo.dao.UserDo;
import cn.xwt.weidisk.pojo.dto.RegData;
import cn.xwt.weidisk.pojo.dto.Resp;
import cn.xwt.weidisk.service.CommonService;
import cn.xwt.weidisk.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 薛慰涛
 */
@RestController
@RequestMapping("/open")
public class OpenController {

    @Resource
    CommonService commonService;
    @Resource
    UserService userService;

    /**
     * 获取验证码
     * @param email 接受验证码的邮箱
     * @param isRegister 是否是注册
     * @return Resp
     */
    @GetMapping("/get-verification-code")
    public Resp getVerificationCode(@RequestParam String email,
                                    @RequestParam(defaultValue = "false") boolean isRegister) {
        // 判断邮箱是否存在
        if(isRegister && userService.existsEmail(email)) {
            return new Resp("A0111", "邮箱已存在");
        }
        if(commonService.getVerificationCode(email)) {
            return Resp.success();
        }
        return new Resp("A0153", "请输入正确的邮箱");
    }

    /**
     * 用户注册
     * @param regData username password email code
     * @return resp
     */
    @PostMapping("/register-user")
    public Resp registerUser(@RequestBody RegData regData) {
        ServiceError serviceError = userService.registerUser(regData);
        switch (serviceError) {
            case USERNAME_EXISTS:
                return new Resp(ErrorCode.USERNAME_ALREADY_EXISTS.getCode(), "用户名已被注册");
            case EMAIL_EXISTS:
                return new Resp(ErrorCode.USERNAME_ALREADY_EXISTS.getCode(), "邮箱已被注册");
            case CODE_ERROR:
                return new Resp(ErrorCode.INCORRECT_VERIFICATION_CODE.getCode(), "验证码错误");
            case SUCCESS:
                return Resp.success();
            default:
                return Resp.serverError();
        }
    }

    /**
     * 获取用户登录信息
     * @return Resp
     */
    @GetMapping("/login-info")
    public Resp getLoginInfo() {
        try {
            UserDo user = (UserDo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            Map<String, String> userData = new HashMap<>(2);
            userData.put("username", user.getUsername());
            userData.put("role", user.getRole().replace("ROLE_", ""));
            return new Resp(ErrorCode.SUCCESS.getCode(), "操作成功", userData);
        } catch (Exception e) {
            return new Resp(ErrorCode.USER_LOGIN_EXCEPTION.getCode(), "没有用户信息");
        }
    }
}
